package JDBC;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.*;

public class TransAction {
    public static void main(String[] args) {
        //获取连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        Connection conn = null;

        try {
            //连接池中获取一个连接
            conn = dataSource.getConnection();
            //开启事物
            conn.setAutoCommit(false);

            //模拟转账
            QueryRunner queryRunner = new QueryRunner(dataSource);
            String sql1 = "update transaaction set balance = balance - ? where name = ?";
            Object[] param1 = {200,"张三"};
            int a = queryRunner.update(conn,sql1,param1);
            System.out.println("a是否操作 ? 1->ok : 0 -> not "+ a);

            int i = 1 / 0;   //报错

            String sql2 = "update transaaction set balance = balance + ? where name = ?";
            Object[] params2 = {200,"李四"};
            int b = queryRunner.update(conn,sql2,params2);
            System.out.println("a是否操作 ? 1->ok : 0 -> not " + b);

            conn.commit(); //提交
            System.out.println("交易成功");

        } catch (SQLException throwables) {
            try {
                conn.rollback();  //错误则回滚
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }
    }
}